﻿using System;

namespace Adaptive.Foundation.Tokenizers
{
    /// <summary>
    /// Provides a custom collection definition for storing <see cref="RawToken"/> types.
    /// </summary>
    public sealed class RawTokenCollection : GenericCollectionBase<RawToken>
    {

        /*--------------------------------------------------------------------------------
         * Constructor / Dispose Methods
         *------------------------------------------------------------------------------*/
        #region Constructor / Dispose Methods
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        /// <remarks>
        /// This is the default constructor.
        /// </remarks>
        public RawTokenCollection()
            : base()
        {
        }
        #endregion

        /*--------------------------------------------------------------------------------
         * Protected Methods
         *------------------------------------------------------------------------------*/
        #region Protected Methods
        /// <summary>
        /// Adds the specified new object to be added.
        /// </summary>
        /// <param name="newObjectToBeAdded">The new object to be added.</param>
        /// <exception cref="ArgumentNullException">When the <i>newObjectToBeAdded</i> is <b>null</b>.
        /// </exception>
        public override void Add(RawToken newObjectToBeAdded)
        {
            RawToken previous = null;

            //Get the last item in the list.
            previous = this[Count - 1];
            if (previous != null)
            {
                previous.NextToken = newObjectToBeAdded;
                newObjectToBeAdded.PreviousToken = previous;
            }
            base.Add(newObjectToBeAdded);
        }
        /// <summary>
        /// Provides a the reference key value for adding the item to the internal reference
        /// key list.
        /// </summary>
        /// <param name="newObjectToBeAdded">The object to be added to the collecton.</param>
        /// <returns>
        /// A reference key used to identify the instance.
        /// </returns>
        protected override string GetKeyForObject(RawToken newObjectToBeAdded)
        {
            if (newObjectToBeAdded.Name.Length > 0)
                return newObjectToBeAdded.Name;
            else if (newObjectToBeAdded.ItemIndex > -1)
                return newObjectToBeAdded.ItemIndex.ToString();
            else
            {
                newObjectToBeAdded.ItemIndex = Count - 1;
                return (Count-1).ToString();
            }
        }
        #endregion
    }
}